package com.cangxuan.manage.interceptor;

import com.cangxuan.manage.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 管理员 拦截器
 */
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    RedisTemplate<String, Object> redisTemplate;

    public AdminInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行了AdminInterceptor拦截器了");
        Thread.sleep(2000);

        //从请求头中获取凭证
        String sign = request.getHeader("Authorization");
        if (sign == null) {
            throw new ServiceException(401, "请传递凭证");
        }

        //根据sign从redis中获取对应用户信息
        Object username = redisTemplate.opsForValue().getAndExpire("admin-" + sign, 30, TimeUnit.MINUTES);
        if (username == null) {
            throw new ServiceException(401, "身份认证失败，请登录");
        }
        log.info("管理已登录.......");

        return true;
    }
}
